package com.payment.system.service.impl;

import com.payment.common.base.AjaxResult;
import com.payment.common.support.Convert;
import com.payment.system.domain.OrderGg;
import com.payment.system.mapper.OrderGgMapper;
import com.payment.system.service.IOrderGgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 光谷订单对账 服务层实现
 *
 * @author payment
 * @date 2019-09-18
 */
@Service
public class OrderGgServiceImpl implements IOrderGgService {
    @Autowired
    private OrderGgMapper orderGgMapper;

    /**
     * 查询光谷订单对账信息
     *
     * @param id 光谷订单对账ID
     * @return 光谷订单对账信息
     */
    @Override
    public OrderGg selectOrderGgById(Long id) {
        return orderGgMapper.selectOrderGgById(id);
    }

    /**
     * 查询光谷订单对账列表
     *
     * @param orderGg 光谷订单对账信息
     * @return 光谷订单对账集合
     */
    @Override
    public List<OrderGg> selectOrderGgList(OrderGg orderGg) {
        return orderGgMapper.selectOrderGgList(orderGg);
    }

    /**
     * 新增光谷订单对账
     *
     * @param orderGg 光谷订单对账信息
     * @return 结果
     */
    @Override
    public int insertOrderGg(OrderGg orderGg) {
        return orderGgMapper.insertOrderGg(orderGg);
    }

    /**
     * 修改光谷订单对账
     *
     * @param orderGg 光谷订单对账信息
     * @return 结果
     */
    @Override
    public int updateOrderGg(OrderGg orderGg) {
        return orderGgMapper.updateOrderGg(orderGg);
    }

    /**
     * 删除光谷订单对账对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteOrderGgByIds(String ids) {
        return orderGgMapper.deleteOrderGgByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除订单
     *
     * @param uploadTime 插入时间
     * @return
     */
    @Override
    public int deleteOrderGuangGuByDateTime(String uploadTime) {
        return orderGgMapper.deleteOrderGuangGuByDateTime(uploadTime);
    }

    @Override
    public AjaxResult orderGuangGuRecord(String insertTime) {
        //删除无卡订单：无卡订单不需要对账,因上游不区分无卡和养卡代付，本地通过交易费率和代付笔数费进行删除
        orderGgMapper.deleteOrderGgByInsertTimeAndProAndPayRate(insertTime, new BigDecimal("3"), new BigDecimal("0.65"));
        //根据userid 进行分组查询，
        List<OrderGg> orderGgList = orderGgMapper.selectOrderGgListByInsertTime(insertTime);
        if (orderGgList == null) {
            return AjaxResult.success("暂无需要对账的订单");
        }
        for (OrderGg orderGg : orderGgList) {
            //初始化 消费总金额/ 还款总金额/ 需要删除的id
            BigDecimal saleAmount = BigDecimal.ZERO;
            BigDecimal paymentAmount = BigDecimal.ZERO;
            String ids = "";
            //查询成功的消费订单 【小额】
            List<OrderGg> saleMinList = orderGgMapper.selectOrderGgListByUserIdAndPayRate(insertTime, orderGg.getBankNumber(), orderGg.getAcqUserId(), new BigDecimal("0.69"));
            //查询成功的消费订单 【大额】
            List<OrderGg> saleMaxList = orderGgMapper.selectOrderGgListByUserIdAndPayRate(insertTime, orderGg.getBankNumber(), orderGg.getAcqUserId(), new BigDecimal("0.79"));
            if (saleMinList != null) {
                for (OrderGg orderSaleMin : saleMinList) {
                    ids += orderSaleMin.getId().toString() + ",";
                    //需要扣除的手续费
                    BigDecimal payRate = orderSaleMin.getOrderAmount().multiply(orderSaleMin.getPayRate().divide(new BigDecimal("100")));
                    saleAmount = saleAmount.add(orderSaleMin.getOrderAmount().subtract(payRate));
                }
            }
            if (saleMaxList != null) {
                for (OrderGg orderSaleMax : saleMaxList) {
                    //需要扣除的手续费
                    ids += orderSaleMax.getId().toString() + ",";
                    BigDecimal payRate = orderSaleMax.getOrderAmount().multiply(orderSaleMax.getPayRate().divide(new BigDecimal("100")));
                    saleAmount = saleAmount.add(orderSaleMax.getOrderAmount().subtract(payRate));
                }

            }
            //查询成功的出款订单
            List<OrderGg> paymentList = orderGgMapper.selectOrderGgListByUserIdAndPro(insertTime, orderGg.getBankNumber(), orderGg.getAcqUserId(), new BigDecimal("1"));
            if (paymentList != null) {
                for (OrderGg orderPayment : paymentList) {
                    ids += orderPayment.getId().toString() + ",";
                    paymentAmount = paymentAmount.add(orderPayment.getOrderAmount());
                }
                paymentAmount.setScale(0, BigDecimal.ROUND_DOWN);
            }
            //消费金额等于出款金额代表订单正常，正常删除消费订单和出款订单
            BigDecimal disparity = paymentAmount.subtract(saleAmount).setScale(0, BigDecimal.ROUND_DOWN);
            if (disparity.abs().compareTo(new BigDecimal("1")) <= 0) {
                orderGgMapper.deleteOrderGgByIds(Convert.toStrArray(ids));
            }
        }
        return AjaxResult.success("成功");
    }


    /**
     * 用户id，卡号进行查询订单
     */
    @Override
    public List<OrderGg> selectOrderListByBankNumber(String insertTime, String userId, String userName, String bankNumber) {
        return orderGgMapper.selectOrderListByBankNumber(insertTime, userId, userName, bankNumber);
    }

    @Override
    public AjaxResult orderGuangGuRecordNew(List<OrderGg> list) {
        Map<String, List<OrderGg>> map = new HashMap<>();
        for (OrderGg orderGg : list) {
            boolean flag = map.containsKey(orderGg.getBankNumber());
            if (flag) {
                List<OrderGg> orderYxList = map.get(orderGg.getBankNumber());
                orderYxList.add(orderGg);
            } else {
                List<OrderGg> list1 = new ArrayList<>();
                list1.add(orderGg);
                map.put(orderGg.getBankNumber(), list1);
            }
        }
        Iterator<Map.Entry<String, List<OrderGg>>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, List<OrderGg>> entry = iter.next();
            BigDecimal saleAmount = BigDecimal.ZERO;
            BigDecimal paymentAmount = BigDecimal.ZERO;
            for (OrderGg orderGg : entry.getValue()) {
                //uploadType 0消费 1出款
                if (orderGg.getOrderType() == 0) {
                    BigDecimal payRate = orderGg.getOrderAmount().multiply(orderGg.getPayRate().divide(new BigDecimal("100")));
                    saleAmount = saleAmount.add(orderGg.getOrderAmount().subtract(payRate));
                } else {
                    paymentAmount = paymentAmount.add(orderGg.getOrderAmount());
                }
            }
            BigDecimal disparity = paymentAmount.subtract(saleAmount).setScale(0, BigDecimal.ROUND_DOWN);
            if (disparity.abs().compareTo(new BigDecimal("1")) <= 0) {
                continue;
            } else {
                for (OrderGg orderGgNow : entry.getValue()) {
                    orderGgMapper.insertOrderGg(orderGgNow);
                }
            }
        }
        return AjaxResult.success("导入成功");
    }

}
